<template>
  <div class="goods-view">
<!--    卡片区域-->
    <el-card class="box-card">
      <!--    筛选区域-->
      <el-form :inline="true" :model="searchObj" class="demo-form-inline" ref="goodsFilterRef" :rules="goodsFilterRules">
        <el-form-item label="名称" prop="searchValue">
          <el-input
            placeholder="请输入商品名"
            v-model="searchObj.searchValue"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="最小价格" prop="minPrice">
          <el-input
            placeholder="请输入最小值"
            v-model="searchObj.minPrice"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="最大价格" prop="maxPrice">
          <el-input
            placeholder="请输入最大值"
            v-model="searchObj.maxPrice"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="一级分类" prop="FCateId">
          <el-select
            v-model="searchObj.FCateId"
            placeholder="一级分类"
            @focus="getGoodsFCate">
            <el-option v-for="item in fCateList" :label="item.fcatename" :value="item.fcateid" :key="item.fcateid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" prop="SCateId">
          <el-select
            v-model="searchObj.SCateId"
            placeholder="二级分类"
            :disabled="!searchObj.FCateId"
            @focus="getGoodsScate(searchObj.FCateId)">
            <el-option v-for="item in sCateList" :label="item.scatename" :value="item.scateid" :key="item.scateid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getNewRenderGoodsList">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetFilterForm">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addNewGood">添加商品</el-button>
        </el-form-item>
      </el-form>
<!--      分页区域-->
      <el-pagination
        :page-size="4"
        layout="prev, pager, next"
        :total="totalNum"
        @current-change="changePageNum">
      </el-pagination>
      <!--    表格区域-->
      <el-table
        :data="readyToRenderGoodsList"
        border
        style="width: 100%">
        <el-table-column
          prop="goodsid"
          label="商品id"
          width="80">
        </el-table-column>
        <el-table-column
          prop="goodsname"
          label="商品名"
          width="600">
        </el-table-column>
        <el-table-column
          label="图片简介"
          width="130">
          <template v-slot:default="scope">
            <img :src="scope.row.goodsimg" alt="">
          </template>
        </el-table-column>
        <el-table-column
          prop="fname"
          label="一级分类名"
          min-width="120">
        </el-table-column>
        <el-table-column
          prop="sname"
          label="二级分类名"
          min-width="120">
        </el-table-column>
        <el-table-column
          label="商品基价"
          width="180">
          <template v-slot:default="scope">
            <span>&yen; {{ scope.row.goodsbaseprice.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="上架日期"
          width="180">
          <template v-slot:default="scope">
            <span>{{ scope.row.shelvesdate.split('T')[0] }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          min-width="240">
          <template v-slot:default="scope">
            <el-button type="primary" icon="el-icon-edit" @click="editCurrentGood(scope.row)">编辑</el-button>
            <el-button type="primary" icon="el-icon-zoom-in" @click="getCurrentDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
<!--    商品详细信息的Dialog对话框-->
    <el-dialog
      title="详情"
      :visible.sync="detailDialogVisible"
      width="60%"
      top="10vh"
      center
      @close="closeGoodDetailDialog">
<!--      展示商品属性及选项值-->
      <div class="attr-choice-area" v-for="(item, index) in [...new Set(this.goodsAttrAndChoice.map(item => item.attrname))]" :key="index">
        <span >{{ item }}</span>
        <div class="choice-area">
          <el-tag v-for="item2 in goodsAttrAndChoice.filter(val => val.attrname === item)" :key="item2.choiceid">{{ item2.choicename }}</el-tag>
        </div>
      </div>
<!--      展示选项值搭配-->
      <div class="collocation">
        <span>可选搭配</span>
        <el-table :data="choiceCollocation">
          <el-table-column property="chiocename" label="搭配名" width="400"></el-table-column>
          <el-table-column property="priceSub" label="价格差"></el-table-column>
          <el-table-column label="售价">
            <template v-slot:default="scope">
              <span>&yen; {{ (scope.row.goodsbaseprice + scope.row.priceSub).toFixed(2) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
<!--    编辑在售商品的对话框-->
    <el-dialog
      title="编辑"
      :visible.sync="editGoodDialogVisible"
      width="60%"
      top="10vh"
      center
      @close="closeGoodEditDialog">
      <!--      展示商品名-->
      <div class="collocation">
        <span>名称</span>
        <el-input v-model="editGoodsObj.goodsname" maxlength="180"></el-input>
      </div>
<!--      商品基价-->
      <div class="collocation">
        <span>商品基价</span>
        <el-input type="number" v-model="editGoodsObj.goodsbaseprice"></el-input>
      </div>
<!--      展示商品所属分类-->
      <div class="collocation">
        <span>所属分类</span>
        <el-select v-model="editGoodsObj.fcateid" placeholder="一级分类">
          <el-option
            v-for="item in fCateList"
            :key="item.fcateid"
            :label="item.fcatename"
            :value="item.fcateid">
          </el-option>
        </el-select>
        <el-select v-model="editGoodsObj.scateid" placeholder="二级分类" @focus="getGoodsScate(editGoodsObj.fcateid)">
          <el-option
            v-for="item in sCateList"
            :key="item.scateid"
            :label="item.scatename"
            :value="item.scateid">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeGoodEditDialog">取 消</el-button>
        <el-button type="primary" @click="submitEditGoodInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!--    商品详细信息的Dialog对话框-->
    <el-dialog
      title="上架商品"
      :visible.sync="newGoodDialogVisible"
      width="60%"
      top="10vh"
      center
      @close="closeNewGoodDialog">
      <el-form ref="newGoodFormRef" :model="newGoodForm" label-width="80px" :rules="newGoodDialogRules">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="newGoodForm.name"></el-input>
        </el-form-item>
        <el-form-item label="商品基价" prop="basePrice">
          <el-input v-model="newGoodForm.basePrice" type="number"></el-input>
        </el-form-item>
        <el-form-item label="上架日期" prop="shelfdate">
          <el-date-picker
            v-model="newGoodForm.shelfdate"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="一级分类" prop="fid">
          <el-select
            v-model="newGoodForm.fid"
            placeholder="一级分类"
            @focus="getGoodsFCate">
            <el-option v-for="item in fCateList" :label="item.fcatename" :value="item.fcateid" :key="item.fcateid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" prop="sid">
          <el-select
            v-model="newGoodForm.sid"
            placeholder="二级分类"
            :disabled="!newGoodForm.fid"
            @focus="getGoodsScate(newGoodForm.fid)"
            style="margin-left: 20px">
            <el-option v-for="item in sCateList" :label="item.scatename" :value="item.scateid" :key="item.scateid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品海报">
          <el-upload
            class="upload-demo"
            name="avatar"
            drag
            action="http://localhost:8888/postsimgs"
            :on-success="upLoadSuccess">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品属性">
          <el-tag
            :key="tag"
            v-for="tag in dynamicTagsList"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
            style="margin: 15px">
            {{ tag }}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="editTagNameVisible"
            v-model="editTagName"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
            style="width: 200px;"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+新增属性</el-button>
        </el-form-item>
        <el-form-item label="基选项值">
          <el-tag
            :key="tag"
            v-for="tag in dynamicTagsValueList"
            :disable-transitions="false"
            style="margin: 15px">
            {{ tag }}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="editTagValueNameVisible"
            v-model="editTagValueName"
            ref="saveTagValueInput"
            size="small"
            @keyup.enter.native="handleInputValueConfirm"
            @blur="handleInputValueConfirm"
            style="width: 200px;"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showValueInput">+新增属性</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeNewGoodDialog">取 消</el-button>
        <el-button type="primary" @click="submitAddGoodInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapMutations, mapState } from 'vuex'
export default {
  name: 'GoodsView',
  created() {
    this.getMerchantSellingGoods()
  },
  data() {
    const checkMaxPrice = (rule, value, callback) => {
      if (!this.searchObj.minPrice && !value) return callback()
      if (value && !this.searchObj.minPrice) return callback(new Error('此时最小价格必填'))
      if (value <= this.searchObj.minPrice) return callback(new Error('此项必须大于最小价格'))
      callback()
    }
    return {
      // 商家号 唯一标识
      merchantId: '',
      // 带渲染的商品列表数据
      readyToRenderGoodsList: [],
      // 商家在售商品详细资料信息
      goodsDetailList: [],
      // 控制商品详细信息的Dialog对话框是否可见
      detailDialogVisible: false,
      // 商品属性及属性选项值概况
      goodsAttrAndChoice: [],
      // 商品属性选项值搭配情况及售价
      choiceCollocation: [],
      // 筛选搜查对象
      searchObj: {
        // 商品名模糊查询
        searchValue: '',
        // 商品价格最小值
        minPrice: '',
        // 商品价格最大值
        maxPrice: '',
        // 商品一级分类Id
        FCateId: '',
        // 商品二级分类Id
        SCateId: ''
      },
      // 商品一级分类列表
      fCateList: [],
      // 商品二级分类列表
      sCateList: [],
      // 筛选条件的表单校验规则
      goodsFilterRules: {
        minPrice: [
          { min: 0, trigger: 'blur' }
        ],
        maxPrice: [
          { min: 0, trigger: 'blur' },
          { validator: checkMaxPrice, trigger: 'blur' }
        ]
      },
      // 正在等待修改的商品对象
      editGoodsObj: {},
      // 控制是否展示编辑商品的对话框
      editGoodDialogVisible: false,
      // 当前页面数据页码 默认为1
      currentPageNum: 1,
      // 当前渲染在界面上的商品总量
      totalNum: 0,
      // 控制是否展示添加新商品信息的对话框
      newGoodDialogVisible: false,
      // 新增商品信息的表单对象
      newGoodForm: {
        name: '',
        basePrice: '',
        shelfdate: '',
        fid: '',
        sid: ''
      },
      newGoodDialogRules: {
        name: [
          { required: true, message: '请填写商品名称', trigger: 'blur' }
        ],
        basePrice: [
          { required: true, min: 0.01, message: '商品基价', trigger: 'blur' }
        ],
        shelfdate: [
          { required: true, message: '请填写商家日期', trigger: 'blur' }
        ],
        fid: [
          { required: true, message: '请选择父分类', trigger: 'blur' }
        ],
        sid: [
          { required: true, message: '请选择子分类', trigger: 'blur' }
        ]
      },
      // 商品海报在express服务器位置的路径
      newGoodPic: '',
      // 新增商品dialog对话框中的属性列表
      dynamicTagsList: [],
      // 当点击 新增属性 时切换显示input框
      editTagNameVisible: false,
      // input框中的所填写值
      editTagName: '',
      // 属性选项值定价为0的初始选项值  他的长度和 dynamicTagsList 一致
      dynamicTagsValueList: [],
      // 控制商品属性选项值编辑input框是否可见的变量
      editTagValueNameVisible: false,
      // 将编辑商品属性选项值input框内容双向绑定的变量
      editTagValueName: ''
    }
  },
  computed: {
    ...mapState(['sellingGoodsList'])
  },
  watch: {
    // 侦听到一级分类id选中号发生变化时 重置二级分类选中号的值
    'searchObj.FCateId'(newVal, oldVal) {
      this.searchObj.SCateId = ''
    },
    'editGoodsObj.fcateid'(newVal, oldVal) {
      if (oldVal === undefined) return
      this.editGoodsObj.scateid = ''
    },
    'newGoodForm.fid'(newVal, oldVal) {
      if (oldVal === undefined) return
      this.newGoodForm.sid = ''
    }
  },
  methods: {
    ...mapMutations(['setSellingGoodsList']),
    // 获取商家在售商品列表信息
    async getMerchantSellingGoods() {
      if (this.sellingGoodsList.length > 0) {
        this.totalNum = this.sellingGoodsList.length
        return (this.readyToRenderGoodsList = this.sellingGoodsList.slice(0, 4))
      }
      this.merchantId = sessionStorage.getItem('id')
      if (!this.merchantId) return this.$message('状态异常')
      console.log('发起远程请求商品数据 商品界面')
      const { data: res } = await this.$http.get('/merchant/goods', {
        params: {
          id: this.merchantId,
          page: this.currentPageNum
        }
      })
      this.totalNum = res.recordset.length
      if (res.meta.status !== 200) return this.$message.error('请求商品数据失败')
      this.setSellingGoodsList(res.recordset)
      this.readyToRenderGoodsList = this.sellingGoodsList.slice(0, 4)
    },
    // 当界面编辑按钮被点击时触发 修改当前商品属性
    editCurrentGood(goodObj) {
      this.editGoodsObj = {
        goodsid: goodObj.goodsid,
        goodsname: goodObj.goodsname,
        goodsbaseprice: goodObj.goodsbaseprice,
        fcateid: goodObj.fcateid,
        scateid: goodObj.scateid
      }
      this.getGoodsFCate()
      this.getGoodsScate(this.editGoodsObj.fcateid)
      this.editGoodDialogVisible = true
    },
    // 当界面中的详情按钮被点击时触发 查看当前商品的详细信息
    async getCurrentDetail(goodObj) {
      const { data: res } = await this.$http.get('/merchant/goodsdetail', {
        params: {
          id: goodObj.goodsid
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取详细信息失败')
      this.detailDialogVisible = true
      this.goodsAttrAndChoice = res.recordset
      this.choiceCollocation = res.recordsets[1]
    },
    // 商品详细信息的dialog对话框关闭时触发
    closeGoodDetailDialog() {
      this.detailDialogVisible = false
    },
    // 获取一级分类信息
    async getGoodsFCate() {
      if (this.fCateList.length > 0) return
      const { data: res } = await this.$http.get('/goods/fcate')
      if (res.meta.status !== 200) return this.$message.error('获取分类信息失败')
      this.fCateList = res.recordset
    },
    // 获取二级分类信息
    async getGoodsScate(fid) {
      const { data: res } = await this.$http.get('/goods/scate', {
        params: {
          id: fid
        }
      })
      this.sCateList = res.recordset
    },
    // 当重置按钮被点击时触发 重置商品列表筛选表单
    resetFilterForm() {
      this.$refs.goodsFilterRef.resetFields()
      this.readyToRenderGoodsList = this.sellingGoodsList.slice(0, 4)
      this.totalNum = this.sellingGoodsList.length
    },
    // 查询按钮被点击时触发 根据用户填入的筛选条件重新获取商品列表数据
    getNewRenderGoodsList() {
      if (!this.searchObj.searchValue && !this.searchObj.SCateId && !this.searchObj.FCateId && !this.searchObj.maxPrice && !this.searchObj.minPrice) return this.$message.info('未选择任何筛选条件')
      this.$refs.goodsFilterRef.validate(valid => {
        if (!valid) return this.$message.error('请修改筛选条件')
        // 获取满足条件的readyToRenderGoodsList
        this.readyToRenderGoodsList = this.sellingGoodsList.filter(item => {
          return (this.searchObj.searchValue ? item.goodsname.includes(this.searchObj.searchValue) : true) & (this.searchObj.minPrice ? item.goodsbaseprice >= this.searchObj.minPrice : true) & (this.searchObj.maxPrice ? item.goodsbaseprice <= this.searchObj.maxPrice : true) & (this.searchObj.FCateId ? item.fcateid === this.searchObj.FCateId : true) & (this.searchObj.SCateId ? item.scateid === this.searchObj.SCateId : true)
        })
        this.totalNum = this.readyToRenderGoodsList.length
        console.log(Object.keys(this.searchObj))
      })
    },
    // 当编辑商品对话框被关闭时触发
    closeGoodEditDialog() {
      this.editGoodDialogVisible = false
      this.editGoodsObj = {}
    },
    // 当确定按钮被触发，提交当前修改商品信息
    async submitEditGoodInfo() {
      const { data: res } = await this.$http.put('/merchant/modifygood', this.editGoodsObj)
      if (res.meta.status !== 200) return this.$message.success('修改失败')
      this.$message.success('修改成功')
      // 关闭笔记窗口并刷新界面
      this.closeGoodEditDialog()
      this.getMerchantSellingGoods()
    },
    // 当当前页数发生改变时触发
    changePageNum(currentPage) {
      this.currentPageNum = currentPage
      // this.getMerchantSellingGoods()
      this.readyToRenderGoodsList = this.sellingGoodsList.slice((this.currentPageNum - 1) * 4, this.currentPageNum * 4)
    },
    // 当添加商品按钮被点击时触发 商家上架新的在售商品
    addNewGood() {
      this.newGoodDialogVisible = true
    },
    // 当新增商品信息对话框被关闭时触发
    closeNewGoodDialog() {
      this.$refs.newGoodFormRef.resetFields()
      this.newGoodDialogVisible = false
      this.newGoodPic = ''
    },
    // 商品图片上传成功后的回调函数
    upLoadSuccess(res) {
      this.newGoodPic = res
    },
    // 用户确认自己所输入的商品属性值 将用户填写的值追加到 dynamicTagsList 中
    handleInputConfirm() {
      if (this.editTagName.trim() === '' || this.dynamicTagsList.findIndex(item => item === this.editTagName) >= 0) {
        this.editTagNameVisible = false
        return
      }
      this.dynamicTagsList.push(this.editTagName)
      this.editTagName = ''
      this.editTagNameVisible = false
    },
    // 用户确认自己所输入的商品属性选项值 将用户填写的值追加到 dynamicTagsList 中
    handleInputValueConfirm() {
      if (this.editTagValueName.trim() === '' || this.dynamicTagsValueList.findIndex(item => item === this.editTagValueName) >= 0) {
        this.editTagValueNameVisible = false
        return
      }
      this.dynamicTagsValueList.push(this.editTagValueName)
      this.editTagValueName = ''
      this.editTagValueNameVisible = false
    },
    // 新增属性选项值按钮被点击时 切换按钮与输入框之间的显示
    showValueInput() {
      this.editTagValueNameVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagValueInput.focus()
      })
    },
    // 新增属性按钮被点击时 切换按钮与输入框之间的显示
    showInput() {
      this.editTagNameVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      })
    },
    // 商品属性tag标签被删除时移除此商品的属性记录
    handleClose(tag) {
      const index = this.dynamicTagsList.findIndex(item => item === tag)
      this.dynamicTagsList.splice(index, 1)
      this.dynamicTagsValueList.splice(index, 1)
    },
    // 当新只能商品对话框中的确定按钮被点击时触发
    submitAddGoodInfo() {
      this.$refs.newGoodFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整信息')
        if (this.dynamicTagsList.length !== this.dynamicTagsValueList.length) return this.$message.error('属性值个数和基本选项值个数必须相同')
        if (this.dynamicTagsList.length === 0) return this.$message.error('新增商品至少有一个商品属性')
        const { data: res } = await this.$http.post('/good/add', {
          gname: this.newGoodForm.name,
          price: this.newGoodForm.basePrice,
          shelfdate: this.newGoodForm.shelfdate,
          mid: sessionStorage.getItem('id'),
          fid: this.newGoodForm.fid,
          sid: this.newGoodForm.sid,
          img: this.newGoodPic,
          aname: this.dynamicTagsList,
          cname: this.dynamicTagsValueList
        })
        if (res.meta.status !== 200) return console.log(res)
        this.newGoodDialogVisible = false
        // 新增上架商品成功后刷新界面
        this.getMerchantSellingGoods()
        this.$message.info('请及时为商品添加属性选项值及库存')
      })
    }
  }
}
</script>

<style scoped lang="less">
.el-pagination {
  text-align: left;
}

.cell img {
  width: 130px;
  height: 130px;
}

.choice-area {
  padding: 20px;
  .el-tag {
    margin-right: 10px;
  }
}

.collocation {
  .el-table,
  .el-input {
    padding: 20px;
  }
  .el-select {
    margin: 10px;
  }
}

</style>
